﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using shop.service;
using shop.entity;
using shop.exception;
using shop.util;
namespace shop.handler
{
    /// <summary>
    /// UserHandler 的摘要说明
    /// </summary>
    public class UserHandler : IHttpHandler, IRequiresSessionState
    {
        private UserService userService = new UserService();
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            string method = context.Request["method"];
            if (method == null || method.Trim().Equals(""))
            {
                //toDo
                printErrorJson(context, "method not error");
            }
            else if (method.Equals("login"))
            {
                Login(context);
            }
            else if (method.Equals("register"))
            {
                Register(context);
            }
            else if (method.Equals("logout"))
            {
                Logout(context);
            }
            else if (method.Equals("add"))
            {
                Add(context);
            }
            else if (method.Equals("toAdminIndex"))
            {
                ToAdminIndex(context);
            }
            else if (method.Equals("update"))
            {
                Update(context);
            }
            else if (method.Equals("delete"))
            {
                Delete(context);
            }
            else
            {
                printErrorJson(context, "method not error");
            }

        }
        protected void Login(HttpContext context)
        {
            string name = context.Request["userName"];
            string password = context.Request["password"];
           int remember = RequestUtil.ParseStringToInt(context.Request,"remember");
            User user = new User()
            {
                Name = name,
                Password = password
            };
            User loginUser = null;
            string json;
            try
            {
                loginUser = userService.Login(user);
                context.Session["user"] = loginUser;
                if (remember==1) {
                    HttpCookie nameCookie= new HttpCookie("username", name);
                    nameCookie.Expires =DateTime.Now.AddDays(7);
                 
                    HttpCookie passwordCookie = new HttpCookie("password", password);
                    passwordCookie.Expires =DateTime.Now.AddDays(7);

                    context.Response.Cookies.Add(nameCookie);
                    context.Response.Cookies.Add(passwordCookie);
                }
                json = JsonUtil.getJsonString(JsonResult<User>.RenderSuccess(loginUser));
            }
            catch (ShopParamException e)
            {
                json = JsonUtil.getJsonString(JsonResult<string>.RenderError(1, e.ErrorMessage));             
            }
            catch (Exception e)
            {
                json = JsonUtil.getJsonString(JsonResult<string>.RenderError(1, e.Message));
            }
            context.Response.Write(json);          
        }
        protected void Register(HttpContext context)
        {
            string name = context.Request["userName"];
            string password = context.Request["password"];
            string rePassword = context.Request["rePassword"];
            User loginUser = new User()
            {
                Name = name,
                Password = password,
                LastLoginTime = DateTime.Now.ToString()
            //RegistStatus = 1,

        };
            string json;
            try
            {
                bool result = userService.Register(loginUser, rePassword);

                //注册成功，直接让用户处于登录状态
                context.Session["user"] = loginUser;
                json = JsonUtil.getJsonString(JsonResult<string>.RenderSuccessMessage("注册成功！"));
            }
            catch (ShopParamException e)
            {
                json = JsonUtil.getJsonString(JsonResult<string>.RenderError(1, e.ErrorMessage));
            }
            catch (Exception e)
            {
                json = JsonUtil.getJsonString(JsonResult<string>.RenderError(1, e.Message));
            }
            context.Response.Write(json);
        }

        protected void Add(HttpContext context)
        {
            string name = context.Request["userName"];
            string password = context.Request["password"];
            string rePassword = context.Request["rePassword"];
            User loginUser = new User()
            {
                Name = name,
                Password = password,
                LastLoginTime = DateTime.Now.ToString()
                //RegistStatus = 1,

            };
            string json;
            try
            {
                bool result = userService.Add(loginUser, rePassword);
                json = JsonUtil.getJsonString(JsonResult<string>.RenderSuccessMessage("添加成功！"));
            }
            catch (ShopParamException e)
            {
                json = JsonUtil.getJsonString(JsonResult<string>.RenderError(1, e.ErrorMessage));
            }
            catch (Exception e)
            {
                json = JsonUtil.getJsonString(JsonResult<string>.RenderError(1, e.Message));
            }
            context.Response.Write(json);
        }
        public void ToAdminIndex(HttpContext context) {
            User loginUser = (User)context.Session["user"];
            if (loginUser != null && loginUser.Rank > 1)
            {
                context.Response.Redirect("/web/view_admin/index.aspx");
            }
            else {
                context.Response.Redirect("/index.aspx");
            }

        }

        private void printErrorJson(HttpContext context, string error)
        {
            context.Response.Write(JsonUtil.getJsonString(JsonResult<string>.RenderError(1, error)));
        }

        private void Update(HttpContext context)
        {

            int id = RequestUtil.ParseStringToInt(context.Request, "id");
            string name = context.Request["name"];
           string password = context.Request["password"];
            string rePassword = context.Request["rePassword"];
            int rankId = RequestUtil.ParseStringToInt(context.Request, "rankId");
            
            User user = new User()
            {
                Name = name,
               Password = password,
                Rank = rankId,
                Id = id
            };
            string json;
            try
            {
                userService.UpdateUser(user,rePassword);

                json = JsonUtil.getJsonString(JsonResult<string>.RenderSuccessMessage("更新用户成功！"));
            }
            catch (ShopParamException e)
            {
                json = JsonUtil.getJsonString(JsonResult<string>.RenderError(1, e.ErrorMessage));
            }
            catch (Exception e)
            {
                json = JsonUtil.getJsonString(JsonResult<string>.RenderError(1, e.Message));
            }
            context.Response.Write(json);
        }

        private void Delete(HttpContext context)
        {
            int id = RequestUtil.ParseStringToInt(context.Request, "id");

            string json;
            bool result = false;
            try
            {
                result = userService.DeleteUser(id);

                json = JsonUtil.getJsonString(JsonResult<string>.RenderSuccessMessage("删除用户成功！"));
            }
            catch (ShopParamException e)
            {
                json = JsonUtil.getJsonString(JsonResult<string>.RenderError(1, e.ErrorMessage));
                return;
            }
            catch (Exception e)
            {
                json = JsonUtil.getJsonString(JsonResult<string>.RenderError(1, e.Message));
            }
            if (!result)
            {
                json = JsonUtil.getJsonString(JsonResult<string>.RenderError(2, "删除用户失败，用户id错误"));

            }
            context.Response.Write(json);
        }

        protected void Logout(HttpContext context)
        {
            context.Session.Clear();
            context.Response.Redirect("/index.aspx");
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}